<!-- const fileList = ref([
  {
    name: "1.jpg",
    url: "https://cdn.jsdelivr.net/gh/themusecatcher/resources@0.0.3/1.jpg",
  },
  {
    name: "Markdown.pdf",
    url: "https://cdn.jsdelivr.net/gh/themusecatcher/resources@0.0.3/Markdown.pdf",
  },
]);
const imageList = ref([
  {
    name: "1.jpg",
    url: "https://cdn.jsdelivr.net/gh/themusecatcher/resources@0.0.3/1.jpg",
  },
]); -->

<template>
  <el-upload
    class="upload-demo"
    drag
    action="#"
    accept=".jpg,.png,.bmp,.jpeg,.psd,.webp"
    :on-change="handleChange"
    :auto-upload="false"
    ref="uploadRef"
    :show-file-list="false"
  >
    <!-- 图片上传框 -->
    <div v-if="!fileList.length">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        Drop file here or <em>click to upload</em>
      </div>
    </div>
    <!-- 回显及遮罩层 -->
    <div v-else>
      <img :src="fileList[0].url" alt="" />
      <div class="mask">
        <el-icon size="50">
          <Edit />
        </el-icon>
        <el-icon size="50" @click.stop="handleDelete">
          <Delete />
        </el-icon>
      </div>
    </div>
    <template #tip>
      <div class="el-upload__tip tip">
        jpg/png files with a size less than 500kb
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { ref } from "vue";
import type { UploadFile, UploadUserFile } from "element-plus";
let fileList = ref<UploadUserFile[]>([]);
const uploadRef = ref();
const handleChange = (file: UploadFile) => {
  //如果上传的图片没有url字段，手动生成
  if (!file.url) file.url = URL.createObjectURL(file.raw as any);
  fileList.value[0] = file;
};
const handleDelete = () => {
  //删除时清除所有已上传图片
  uploadRef.value.clearFiles();
  fileList.value = [];
};
</script>

<style lang="scss" scoped>
:deep(.el-upload) {
  height: 100%;
}
:deep(.el-upload-dragger) {
  height: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}
.upload-demo {
  width: 300px;
  height: 200px;
}
.tip {
  color: red;
}
//遮罩层
.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(100, 100, 100, 0.5);
  color: #ffffff;
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  &:hover {
    opacity: 1;
  }
  .el-icon {
    margin: 0 10px;
    &:hover {
      color: #70aeed;
    }
  }
}
</style>